<template>
  <!-- 当点击 取消按钮 时，关闭弹窗 -->
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="60%"
    top="4vh"
    :append-to-body="true"
    @close="clearDialog()"
    v-loading="loding"
    :destroy-on-close="true"
  >
    <ele-form
      v-model="createData"
      v-bind="formConfig"
      ref="form"
      v-loading="loading"
    ></ele-form>
    <ele-table-editor
      ref="table-editor"
      :isShowAdd="false"
      :isShowDelete="false"
      :columns="columns"
      v-model="capacityTableForm"
    >
      <!-- 容量 -->
      <template v-slot:count="{ data }">{{ data.count }}</template>

      <!-- 数值 -->
      <template v-slot:amount="{ data }">{{
        data.sumCodeNum - data.hasPrintNum
      }}</template>
      <!-- 已打数值 -->
      <template v-slot:hasPrintNum="{ data }">{{ data.hasPrintNum }}</template>
    </ele-table-editor>
    <barcode-print
      :barcodeInfo="barcodeInfoImage"
      ref="print"
      :key="time"
      :isPrint="false"
      v-if="Object.keys(barcodeInfoImage).length > 0"
    ></barcode-print>

    <div slot="footer" class="dialog-footer">
      <el-button @click="clearDialog()">{{ $t("common.cancel") }}</el-button>
      <el-button
        v-if="dialogfrom.isCreateBarcode == 1 && printCodeOk"
        type="primary"
        @click="handleShow"
        >{{ $t("capacityCode.clearCapacityCode") }}</el-button
      >
    </div>

    <el-dialog
      width="50%"
      :title="$t('capacityCode.printFilter')"
      :visible.sync="innerVisible"
      :append-to-body="true"
      @close="clearFormDialog()"
      v-loading="loding"
      :close-on-click-modal="false"
    >
      <ele-table-editor
        ref="table-editor"
        :isShowAdd="false"
        :isShowDelete="false"
        :columns="columns"
        v-model="capacityTableForm"
      >
        <!-- 容量 -->
        <template v-slot:count="{ data }">{{ data.count }}</template>

        <!-- 数值 -->
        <template v-slot:amount="{ data }">
          <el-input-number
            v-model="data.amount"
            :precision="0"
            :min="1"
            :max="data.oldAmount"
          ></el-input-number>
        </template>
        <!-- 已打数值 -->
        <template v-slot:hasPrintNum="{ data }">{{
          data.hasPrintNum
        }}</template>
      </ele-table-editor>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearFormDialog()">
          {{ $t("common.cancel") }}
        </el-button>
        <el-button type="primary" @click="handleRequest">
          {{ $t("common.submit") }}
        </el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  checkCapacityCode, //校验是否已经生成对应类型容量码
  templateType, //获取生码分类
  getProdByOrder, //根据订单获取型号
  selectCommonProduceRelByProduce, //根据型号、分类获取生码规则接口
  getCapacityCodeList, //获取容量/数量列表接口,
  detailbyName,
  splitPrintList, //获取本次要打印的条码信息
  clearCapacityCode,
} from "@/api/print/mesCapacityCode";

import qs from "qs";
import BarcodePrint from "@/components/barcodePrint/barcodePrint";
import EleTableEditor from "ele-table-editor";
let arrBarcodePrintingList2 = [];
import sys from "@/config";

export default {
  name: "barcodePrintingAddModel",
  watch: {
    visible(val, oldVal) {
      if (!val) {
        this.$nextTick(() => {
          this.$refs.form.resetForm();
        });
        this.barcodeInfo = {};
      }
    },
    "createData.barcodePrintTemp": {
      handler(newVal, oldVal) {
        this.getTemplateName(newVal);
      },
      deep: true,
    },
  },
  props: {
    title: {
      type: String,
      default: "",
    },
  },
  components: { BarcodePrint, EleTableEditor },
  data() {
    let that = this;
    return {
      loding: false,
      time: 0,
      capacityTableForm: [],
      // 容量表格
      columns: [
        {
          // el-table-column 的属性
          type: "index",
        },
        {
          // el-table-column 的属性
          prop: "count",
          label: $i18n.t("mesCapacityCodePrinting.volume"),
          // 支持 显示隐藏
          vif: true,
        },
        {
          prop: "amount",
          label: $i18n.t("mesCapacityCodePrinting.unprintedQuantity"),
        },
        {
          prop: "hasPrintNum",
          label: $i18n.t("mesCapacityCodePrinting.quantityPrinted"),
        },
      ],
      formConfig: {
        span: 24,
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        labelPosition: "right",
        formDesc: {
          orderCode: {
            //生产工单编码
            type: "input",
            label: $i18n.t("mesCapacityCodePrinting.orderCode"),
            layout: 12,
            disabled: true,
          },
          printSort: {
            type: "select",
            label: $i18n.t("mesCapacityCodePrinting.printSort"),
            layout: 12,
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              const params = {};
              const list = await templateType(params);
              return list.data.result;
            },
            on: {
              change(val) {
                that.createData.printSort = val;
                (that.formConfig.formDesc.goodsCode.options = async (data) => {
                  const params = {
                    orderCode: data.orderCode,
                  };
                  const list = await getProdByOrder(params);
                  that.goodsCodeList = list.data.result;
                  return list.data.result;
                }),
                  that.changeCode();
              },
            },
            required: true,
            disabled: false,
          },
          goodsCode: {
            //型号
            type: "select",
            label: $i18n.t("mesCapacityCodePrinting.goodsCode"),
            layout: 12,
            prop: {
              value: "prodCode",
              text: "prodName",
            },
            options: async (data) => {
              const params = {
                orderCode: data.orderCode,
              };
              const list = await getProdByOrder(params);
              that.goodsCodeList = list.data.result;
              return list.data.result;
            },
            slots: {
              default(h, options) {
                let data = that.goodsCodeList;
                if (data && data.length > 0) {
                  return data.map((option) =>
                    h("el-option", { attrs: { value: option.prodCode } }, [
                      h("span", { style: { float: "left" } }, option.prodName),
                      h(
                        "span",
                        {
                          style: {
                            float: "right",
                            color: "#8492a6",
                            fontSize: "13px",
                          },
                        },
                        option.prodCode
                      ),
                    ])
                  );
                } else {
                  return [];
                }
              },
            },
            on: {
              change(val) {
                that.createData.goodsCode = val;
                let goodsCodeList = that.goodsCodeList;
                let goodsCode = goodsCodeList.find((item) => {
                  return item.prodCode == val;
                });
                if (goodsCode) {
                  that.createData.productType = goodsCode.productType;
                }
                that.changeCode();
              },
            },
            required: true,
            disabled: false,
          },
          remark: {
            //生产工单编码
            type: "input",
            label: $i18n.t("mesCapacityCodePrinting.inputClearUniqueCodeReason"),
            layout: 12,
            required: true,
          },
        },
      },
      createData: {
        orderCode: null,
        goodsCode: null,
        printSort: null,
        remark: null,
        productType: null,
      },
      goodsCodeList: [],
      detailList: [],
      barcodeInfo: {},
      barcodeInfoImage: {},
      dialogfrom: {},
      visible: false,
      loading: false,
      innerVisible: false,
      printCodeOk: false,
      form: {
        amount: 0,
      },
      rules: {
        amount: [
          {
            required: true,
            message: $i18n.t("mesCapacityCodePrinting.printingQuantity"),
            trigger: "blur",
          },
        ],
      },
      maxnum: 9999,
      list: [],
    };
  },

  methods: {
    //初始化
    init(params) {
      this.dialogfrom = params;
      this.barcodeInfo = params;
      this.createData.orderCode = params.orderCode;
      this.visible = true;
    },

    /**
     * @author bing
     * @since 2022-11-18 14:47:33
     *  箱码打印-获取条码数量，已打印、未打印数量
     */
    async getBoxCount() {
      let res = await getBoxCount({
        orderCode: this.dialogfrom.orderCode,
      });
      let { quantity, quantityPrinted, quantityNotPrinted } = res.data.result;
      this.dialogfrom.printQuantity = quantity;
      this.dialogfrom.quantityPrinted = quantityPrinted;
      this.dialogfrom.quantityNotPrinted = quantityNotPrinted;
      if (!quantity) {
        this.countChange(this.dialogfrom.count);
      }
    },

    async getBarcodePrintTempList() {
      const res = await getBarcodePrintTempList();
      arrBarcodePrintingList2 = res.data.result;
    },
    /**
     * @author bing
     * @since 2022-11-17 11:13:11
     * 清楚箱码
     */
    async clearBoxcode() {
      try {
        let { value } = await this.$prompt(
          $i18n.t("mesCapacityCodePrinting.inputClearUniqueCodeReason2"),
          $i18n.t("common.tip"),
          {
            confirmButtonText: $i18n.t("common.ok"),
            cancelButtonText: $i18n.t("common.cancel"),
            inputValidator: (value) => {
              if (!value) {
                return $i18n.t("mesCapacityCodePrinting.inputClearUniqueCodeReason2");
              }
            },
          }
        );
        if (!value) {
          this.$message.warning(
            $i18n.t("mesCapacityCodePrinting.inputClearUniqueCodeReason2")
          );
          return;
        }
        this.loding = true;
        let res = await clearBoxcode({
          clearReason: value,
          orderCode: this.dialogfrom.orderCode,
        });

        let deflt = this.dialogfrom.count;
        this.dialogfrom.count = 999;
        this.$nextTick(() => {
          this.dialogfrom.count = deflt;

          this.getBoxCount();
          this.$set(this.dialogfrom, "isCreateBarcode", 0);
        });
      } finally {
        this.loding = false;
      }
    },
    //类型型号选择处理
    changeCode() {
      let createData = this.createData;
      let check = {
        orderCode: createData.orderCode,
        prodCode: createData.goodsCode,
        productType: createData.productType,
        capacityType: createData.printSort,
      };
      //当分类和型号都存在时获取效验容量码是否生成
      if (check.capacityType && check.prodCode) {
        this.loading = true;
        checkCapacityCode(check).then((res) => {
          this.loading = false;
          if (res.data.result) {
            getCapacityCodeList(check).then((res) => {
              if (res.data.success) {
                let tableData = res.data.result.barCodeResult;
                this.capacityTableForm = tableData;
                console.log(tableData);
                this.$nextTick(() => {
                  this.dialogfrom.isCreateBarcode = 1;
                  this.printCodeOk = true;
                });
              } else {
                this.capacityTableForm = [];
                this.printCodeOk = false;
              }
            });
          } else {
            this.capacityTableForm = [];
            this.printCodeOk = false;
          }
        });
      }
    },
    //获取模板详情
    getTemplateName(templateName) {
      if (templateName) {
        const params = {
          templateName,
        };
        detailbyName(params).then((res) => {
          if (res.data.success) {
            if (res.data.result.length > 0) {
              this.time = new Date().getTime();
              this.barcodeInfoImage = {
                ...this.barcodeInfo,
                ...res.data.result[0],
              };
            }
          }
        });
      } else {
        this.barcodeInfoImage = {};
      }
    },
    //条码模板选择
    handleChange(e) {
      if (arrBarcodePrintingList2.length == 0) return;
      if (!this.dialogfrom.barcodePrintTemp) return;

      let obj = arrBarcodePrintingList2.find((ite) => {
        return e == ite.templateName;
      });
      this.loading = true;
      printTemplateInfo(obj.id)
        .then((res) => {
          this.time = new Date().getTime();
          this.barcodeInfo = { ...this.barcodeInfo, ...res.data.result };
        })
        .finally((res) => {
          this.loading = false;
        });
    },
    //修改容量
    countChange(e) {
      let quantity = Number(this.dialogfrom.quantity);
      let printQuantity = Math.ceil(quantity / e);
      this.dialogfrom.printQuantity = printQuantity;
    },
    //点击生码按钮
    creatBoxCode() {
      this.$refs.form.validate().then((valid) => {
        let { orderCode, count, barcodePrintTemp, printQuantity } =
          this.dialogfrom;
        let data = {
          orderCode: orderCode, //'生产工单号',
          count: count, //'容量',
          barcodePrintTemp: barcodePrintTemp, //'打印条码模板名称',
        };

        this.$confirm(
          `${$i18n.t("mesCapacityCodePrinting.createMsg1")}${count}${$i18n.t(
            "printBoxCode.createMsg2"
          )}${printQuantity}${$i18n.t("mesCapacityCodePrinting.clearBarcodeSuccess")}`,
          $i18n.t("common.tip"),
          {
            confirmButtonText: $i18n.t("common.ok"),
            cancelButtonText: $i18n.t("common.cancel"),
            type: "warning",
          }
        ).then(() => {
          this.loding = true;
          creatBoxCode(data)
            .then((res) => {
              if (res.data.success) {
                this.$message.success($i18n.t("mesCapacityCodePrinting.createSuccess"));

                let deflt = this.dialogfrom.count;
                this.dialogfrom.count = 999;
                this.$nextTick(() => {
                  this.dialogfrom.count = deflt;
                  this.getBoxCount();

                  this.$set(this.dialogfrom, "isCreateBarcode", 1);
                });
              }
              this.loding = false;
            })
            .catch((err) => {
              this.loding = false;
            });
        });
      });
    },

    clearDialog() {
      this.visible = false;
      this.$emit("refreshList");
      this.capacityTableForm = [];
    },
    clearFormDialog() {
      this.innerVisible = false;
    },
    handleShow() {
      this.$refs.form.validate().then((valid) => {
        if (!valid) {
          const params = {
            orderCode: this.createData.orderCode,
            prodCode: this.createData.goodsCode,
            capacityType: this.createData.printSort,
            productType: this.createData.productType,
            remark: this.createData.remark,
          };
          clearCapacityCode(params).then((res) => {
            if (res.data.result) {
              this.visible = false;
              this.$message.success(
                $i18n.t("mesCapacityCodePrinting.clearBarcodeSuccess")
              );
            }
          });
        }
      });
    },
    //点击打印按钮
    handleRequest() {
      let tableData = this.capacityTableForm;
      let params = [];
      tableData.forEach((item) => {
        let { orderCode, prodCode, capacityType, amount, count, productType } =
          item;
        params.push({
          orderCode,
          prodCode,
          capacityType,
          amount,
          count,
          productType,
        });
      });
      splitPrintList(params).then((res) => {
        if (res.data.success) {
          let list = res.data.result,
            info = { ...this.barcodeInfoImage, ...this.createData },
            infoList = [];
          if (Array.isArray(list) && list.length > 0) {
            list.forEach((item) => {
              infoList.push(item);
            });
          }
          delete info.values;
          info.values = infoList;
          localStorage.splitPrint = JSON.stringify(info);
          this.clearFormDialog();
          this.clearDialog();
          window.open(sys.publicPath + "splitPrint?type=11");
        }
      });
    },
  },
};
</script>
